﻿using BemfaCloud.Devices;
using BemfaCloud;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using BemfaCloud.Connectors.Builder;
using BemfaCloud.Models;
using Microsoft.AspNetCore.DataProtection;

namespace ComputerWorker
{
    public class BemfaManage
    {
        private  IBemfaConnector _connector;
        private readonly ILogger<BemfaManage> _logger;

        public BemfaManage(ILogger<BemfaManage> logger)
        {
            _logger= logger;
        }

        public void Init(string secret, string topic)
        {
            // 创建连接器
            _connector = new BemfaConnectorBuilder()
            .WithTcp()
                .WithSecret(secret) // 使用传入的秘密密钥
                .WithTopics(topic)  // 订阅的主题
                .WithErrorHandler((e) => _logger.LogError(e.Message))
                .WithMessageHandler(HandleMessage)
                .Build();

            // 创建开关设备
            var bemfaSwitchInstance = new BemfaSwitch(topic, _connector);
            bemfaSwitchInstance.On += (e) =>
            {
                _logger.LogInformation("收到打开开关命令");
                return true;
            };
            bemfaSwitchInstance.Off += (e) =>
            {
                _logger.LogInformation("收到关闭开关命令");
                ComputerHelper.ShutDown();
                return true;
            };
            bemfaSwitchInstance.OnException += (e) => _logger.LogError($"发生了异常：{e.Message}");
            bemfaSwitchInstance.OnMessage += (e) => _logger.LogError($"收到无法解析的消息：{e.ToString()}");
        }

        private void HandleMessage(MessageEventArgs e)
        {
            if (e.Type == CommandType.GetTimestamp)
            {
                _logger.LogInformation($"收到消息：{e}");
            }
        }

        /// <summary>
        /// 异步连接到 Bemfa 服务器。
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ConnectAsync()=> await _connector.ConnectAsync();

        /// <summary>
        /// 异步断开与 Bemfa 服务器的连接。
        /// </summary>
        /// <returns></returns>
        public async Task DisconnectAsync()=> await _connector.DisconnectAsync();
    }
}
